package com.weimob.mcloud.wechatwork.customer.mq.model;

import com.weimob.arch.artemis.client.api.exception.ArtemisException;
import com.weimob.artemis.client.producer.ArtemisProducer;
import com.weimob.artemis.client.producer.config.ProducerConfig;
import com.weimob.artemis.client.producer.model.ProducerResponse;
import com.weimob.mcloud.wechatwork.customer.service.user.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author yuzhaoyang
 * @desc 直播后台artemis消息生产者
 * @date
 */
@Component
@Slf4j
public class WechatworkBaseArtemisProducer {

    @Autowired
    private ArtemisProducer artemisProducer;

    private static final int STATUS_CODE_SUCCESS = 0;

    /**
     * 后台业务mq消息发送
     */
    public void send(String user, String topic, String message) {
        Assert.notNull(user, "user must not be null");
        Assert.notNull(topic, "topic must not be null");
        Assert.notNull(message, "message must not be null");
        ProducerResponse producerResponse;
        try {
            producerResponse = artemisProducer.send(
                    ProducerConfig.builder().user(user).build(),
                    topic,
                    message
            );
        } catch (ArtemisException e) {
            log.error("WechatworkBaseArtemisProducer send msg fail!topic:{},user:{},message:{},cause by:{}", topic, user, message, e.getMessage());
            throw new BizException(Long.valueOf(e.getErrorCode().getCode()), e.getMessage());
        }
        if (producerResponse == null) {
            log.error("WechatworkBaseArtemisProducer send msg fail!topic:{},user:{},message:{},cause by:{}", topic, user, message, "producerResponse is null");
            throw new BizException(99999999L, "发送mq异常，未知错误，返回结果为NULL");
        }
        if (STATUS_CODE_SUCCESS != producerResponse.getStatusCode()) {
            log.error("WechatworkBaseArtemisProducer send msg fail!topic:{},user:{},message:{},cause by:{}", topic, user, message, producerResponse.getFailureCause().getMessage());
            throw new BizException((long) producerResponse.getStatusCode(), producerResponse.getFailureCause().getMessage());
        }
        log.info("WechatworkBaseArtemisProducer send msg success!topic:{},user:{},message:{}", topic, user, message);
    }

}
